package com.ad.aidai.fragments.order_detail;

import android.content.Context;
import android.view.View;
import android.widget.Button;

import com.ad.aidai.R;
import com.ad.aidai.bean.Order;
import com.ad.aidai.bean.OrderDetailedBean;
import com.ad.aidai.bean.User;
import com.ad.aidai.common.ADApp;
import com.ad.aidai.common.RxBus;
import com.ad.aidai.common.utils.CheckUtil;
import com.ad.aidai.events.CommonEvent;
import com.ad.aidai.network.NetWork;
import com.ad.aidai.network.StatusCodeFromNet;
import com.ad.aidai.network.result.NetResult;
import com.orhanobut.logger.Logger;
import com.umeng.analytics.MobclickAgent;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import rx.Observer;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
import rx.subscriptions.CompositeSubscription;

/**
 * OrderDetailPresenter
 * <p>
 * Created by Yusxon on 17/1/25.
 */

public class OrderDetailPresenter implements OrderDetailContract.Presenter {

    private Context mContext;
    private OrderDetailContract.View mView;
    private CompositeSubscription mSubscriptions;

    private List<OrderDetailedBean> mOrderData;
    private Map<String, Integer> itemPos;

    public OrderDetailPresenter(Context context, OrderDetailContract.View view) {
        this.mContext = context;
        this.mView = view;
        mView.setPresenter(this);
        initOrderData();
    }

    @Override
    public void subscribe() {
        mSubscriptions = new CompositeSubscription();
    }

    @Override
    public void unSubscribe() {
        mContext = null;
        mView = null;
        mSubscriptions.clear();
        mSubscriptions = null;
    }

    void initOrderData() {
        mOrderData = new ArrayList<>();
        itemPos = new HashMap<>();

        int[] icons = {R.mipmap.icon_order_number, R.mipmap.icon_type, R.mipmap.icon_content, R.mipmap.icon_me_light,
                R.mipmap.icon_me_light, R.mipmap.icon_address, R.mipmap.icon_push_blue, R.mipmap.icon_clock, R.mipmap
                .icon_date, R.mipmap.icon_money};
        String[] titles = {"爱代单号", "", "类型", "内容", "", "发单人", "接单人", "", "交货地点", "推送地点", "", "推送时间", "截止时间", "酬劳"};

        for (int i = 0, j = 0; i < titles.length; ++i) {
            if (CheckUtil.checkStrNull(titles[i])) {
                mOrderData.add(new OrderDetailedBean());
            } else {
                int type = OrderDetailedBean.VIEWTYPE_ONE_LINE;
                if (titles[i].equals("内容") || titles[i].equals("交货地点")) {
                    type = OrderDetailedBean.VIEWTYPE_TWO_LINE;
                }
                itemPos.put(titles[i], i);
                mOrderData.add(new OrderDetailedBean(type, icons[j], titles[i], "--"));
                j++;
            }
        }
    }

    @Override
    public void loadOrderData() {

        if (mOrderData.get(mOrderData.size() - 1).getType() == OrderDetailedBean.VIEWTYPE_BUTTON) {
            mOrderData.remove(mOrderData.size() - 1);
        }

        Order order = ADApp.getOrder();
        String[] type = {"代拿", "代买", "代办"};

        mOrderData.get(itemPos.get("爱代单号")).setValue(order.getOrderId());
        mOrderData.get(itemPos.get("类型")).setValue(type[order.getOrderType()]);
        mOrderData.get(itemPos.get("内容")).setValue(order.getOrderContent());
        mOrderData.get(itemPos.get("发单人")).setType(OrderDetailedBean.VIEWTYPE_HEAD).setValue(order
                .getSendUser());
        mOrderData.get(itemPos.get("接单人")).setValue("未被接");
        if (order.getOrderStatus() != Order.STATUS_NO_RECIEVE && order.getOrderStatus() != Order.STATUS_CANCEL) {
            mOrderData.get(itemPos.get("接单人")).setType(OrderDetailedBean.VIEWTYPE_HEAD).setValue
                    (order.getReceiveUser());
        }
        mOrderData.get(itemPos.get("交货地点")).setValue(order.getOrderExchnPlace());
        mOrderData.get(itemPos.get("推送地点")).setValue(order.getPlace().getPlaceName());
        mOrderData.get(itemPos.get("推送时间")).setValue(order.getOrderSendTime());
        mOrderData.get(itemPos.get("截止时间")).setValue(order.getOrderExpireTime());
        mOrderData.get(itemPos.get("酬劳")).setValue(order.getOrderReward() + "元");

        User me = ADApp.getUser();
        User sendUser = order.getSendUser();
        User receiveUser = order.getReceiveUser();

        String btnText = "";

        if (sendUser.getUserId().equals(me.getUserId())) {
            switch (order.getOrderStatus()) {
                case Order.STATUS_NO_RECIEVE:
                    btnText = "撤销";
                    break;
                case Order.STATUS_NO_ACCEPTANCE:
                    btnText = "完成";
                    break;
                case Order.STATUS_SENDER_NO_SCORE:
                case Order.STATUS_NO_SCORE:
                    btnText = "评分";
                    break;
                case Order.STATUS_CANCEL:
                    break;
                case Order.STATUS_SCORE:
                case Order.STATUS_RECIEVER_STATE:
                case Order.STATUS_RECIEVER_NO_SCORE:
                    btnText = "申述";
                    break;
                default:
                    btnText = "";
                    break;
            }
        } else {
            if (order.getOrderStatus() == Order.STATUS_NO_RECIEVE) {
                btnText = "接单";
            } else if (receiveUser.getUserId().equals(me.getUserId())) {
                switch (order.getOrderStatus()) {
                    case Order.STATUS_NO_ACCEPTANCE:
                        btnText = "";
                        break;
                    case Order.STATUS_RECIEVER_NO_SCORE:
                    case Order.STATUS_NO_SCORE:
                        btnText = "评分";
                        break;
                    case Order.STATUS_SCORE:
                    case Order.STATUS_SENDER_STATE:
                    case Order.STATUS_SENDER_NO_SCORE:
                        btnText = "申述";
                        break;
                    default:
                        btnText = "";
                        break;
                }
            }
        }
        if (!btnText.equals("")) {
            mOrderData.add(new OrderDetailedBean().setType(OrderDetailedBean.VIEWTYPE_BUTTON).setValue
                    (btnText));
        }
        mView.loadOrderDataComplete();
    }

    @Override
    public List<OrderDetailedBean> getOrderData() {
        return mOrderData;
    }

    @Override
    public void clickBtnOrder(View view, int position) {
        Logger.t(this.getClass().getSimpleName()).i("点击按钮");
        switch (view.getId()) {
            case R.id.btn_order:
                Button button = (Button) view;
                switch (button.getText().toString()) {
                    case "接单":
                        if (CheckUtil.checkStrNull(ADApp.getUser().getUserPayNum())) {
                            mView.toast("请先到个人资料页面填写支付宝账号");
                            return;
                        }
                        acceptOrder();
                        break;
                    case "撤销":
                        mView.showDialog("是否撤销该订单?", "撤销");
                        break;
                    case "完成":
                        mView.showDialog("对方是否已完成该订单?", "完成");
                        break;
                    case "评分":
                        mView.gotoComment();
                        break;
                    case "申述":
                        mView.gotoState();
                        break;
                    default:
                        break;
                }
                break;
            default:
                break;
        }
    }

    @Override
    public void clickDialogSure(String btnText) {
        switch (btnText) {
            case "撤销":
                withdrawOrder();
                break;
            case "完成":
                finishOrder();
                break;
            default:
                break;
        }
    }

    @Override
    public void clickItem(View view, int position) {
        switch (mOrderData.get(position).getType()) {
            case OrderDetailedBean.VIEWTYPE_HEAD:

                Order order = ADApp.getOrder();
                User sender = order.getSendUser();
                User receiver = order.getReceiveUser();
                boolean show = false;

                if (sender != null && sender.getUserId().equals(ADApp.getUser().getUserId())) {
                    show = true;
                }
                if (receiver != null && receiver.getUserId().equals(ADApp.getUser().getUserId())) {
                    show = true;
                }

                User user = (User) mOrderData.get(position).getValue();
                mView.openLookProfile(user.getUserId(), show, show);
                break;
            default:
                break;
        }
    }

    /**
     * 接单
     */
    private void acceptOrder() {
        mView.showLoading("接单");
        NetWork.getOrderOperationApi()
                .acceptOrder(ADApp.getOrder().getOrderId(), ADApp.getUser().getUserId())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<NetResult>() {
                    @Override
                    public void onCompleted() {
                    }

                    @Override
                    public void onError(Throwable e) {
                        MobclickAgent.reportError(mContext, e);
                        Logger.t("OrderDetailPresenter").e(e.getMessage());
                        mView.closeLoading(false);
                    }

                    @Override
                    public void onNext(NetResult result) {
                        if (result.getCode() == StatusCodeFromNet.CODE_SUCCESS) {
                            mView.closeLoading(true);
                            ADApp.getOrder().setOrderStatus(Order.STATUS_NO_COMPLETE);
                            ADApp.getOrder().setReceiveUser(ADApp.getUser());
                            ADApp.getOrder().setOrderReceiveId(ADApp.getUser().getUserId());
                            RxBus.getInstance().postEvent(new CommonEvent<>(CommonEvent.ORDER_STATUS_CHANGE, ADApp
                                    .getOrder()));
                        } else {
                            Logger.t("OrderDetailPresenter").e(result.toString());
                            if (result.getCode() == StatusCodeFromNet.CODE_ORDER_HAD_RECEIVER) {
                                mView.toast("订单已经被接，请刷新列表获取最新订单信息");
                            }
                            //停止加载,底部变为点击加载更多
                            mView.closeLoading(false);
                        }
                    }
                });
    }

    /**
     * 撤单
     */
    private void withdrawOrder() {
        mView.showLoading("撤单");
        NetWork.getOrderOperationApi()
                .withdrawOrder(ADApp.getOrder().getOrderId())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<NetResult>() {
                    @Override
                    public void onCompleted() {
                    }

                    @Override
                    public void onError(Throwable e) {
                        MobclickAgent.reportError(mContext, e);
                        Logger.t("OrderDetailPresenter").e(e.getMessage());
                        mView.closeLoading(false);
                    }

                    @Override
                    public void onNext(NetResult result) {
                        if (result.getCode() == StatusCodeFromNet.CODE_SUCCESS) {
                            mView.closeLoading(true);
                            ADApp.getOrder().setOrderStatus(Order.STATUS_CANCEL);
                            RxBus.getInstance().postEvent(new CommonEvent<>(CommonEvent.ORDER_STATUS_CHANGE, ADApp
                                    .getOrder()));
                        } else {
                            Logger.t("OrderDetailPresenter").e(result.toString());
                            //停止加载,底部变为点击加载更多
                            mView.closeLoading(false);
                        }
                    }
                });
    }

    /**
     * 完成单
     */
    private void finishOrder() {
        mView.showLoading("提交");
        NetWork.getOrderOperationApi()
                .finishOrder(ADApp.getOrder().getOrderId())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<NetResult>() {
                    @Override
                    public void onCompleted() {
                    }

                    @Override
                    public void onError(Throwable e) {
                        MobclickAgent.reportError(mContext, e);
                        Logger.t("OrderDetailPresenter").e(e.getMessage());
                        mView.closeLoading(false);
                    }

                    @Override
                    public void onNext(NetResult result) {
                        if (result.getCode() == StatusCodeFromNet.CODE_SUCCESS) {
                            mView.closeLoading(true);
                            ADApp.getOrder().setOrderStatus(Order.STATUS_COMPLETE);
                            RxBus.getInstance().postEvent(new CommonEvent<>(CommonEvent.ORDER_STATUS_CHANGE, ADApp
                                    .getOrder()));
                        } else {
                            Logger.t("OrderDetailPresenter").e(result.toString());
                            //停止加载,底部变为点击加载更多
                            mView.closeLoading(false);
                        }
                    }
                });
    }
}
